import socket
import threading
import subprocess
import os

def handle_client(client_socket, client_address):
    print(f"Accepted connection from {client_address}")
    try:
        while True:
            # 接收客户端发送的数据
            data = client_socket.recv(1024)
            if not data:
                break
            message = data.decode().strip()
            print(f"Received data from {client_address}: {message}")
            
            # 执行消息指定的脚本
            try:
                # 使用subprocess.run执行命令
                result = subprocess.run(message, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
                response = f"STDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}"
            except subprocess.CalledProcessError as e:
                response = f"Error executing command: {e}\nSTDOUT:\n{e.stdout}\nSTDERR:\n{e.stderr}"
            
            # 发送响应数据给客户端
            client_socket.send(response.encode())
    finally:
        # 关闭客户端连接
        client_socket.close()
        print(f"Connection with {client_address} closed")

def main():
    # 创建TCP/IP套接字
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 绑定套接字到地址和端口
    server_address = ('localhost', 10000)
    server_socket.bind(server_address)

    # 监听传入的连接
    server_socket.listen(5)
    print(f"Starting up on {server_address[0]} port {server_address[1]}")

    try:
        while True:
            # 等待一个新的连接
            print("Waiting for a connection...")
            client_socket, client_address = server_socket.accept()
            
            # 创建一个新的线程来处理连接
            client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address))
            client_thread.start()
    except KeyboardInterrupt:
        print("Server is shutting down.")
    finally:
        # 关闭服务器套接字
        server_socket.close()

if __name__ == "__main__":
    main()